package labox.innovation.gameserver;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javolution.util.FastList;
import labox.innovation.config.Config;
import labox.innovation.gameserver.instancemanager.ItemsOnGroundManager;
import labox.innovation.gameserver.model.L2ItemInstance;
import labox.innovation.gameserver.timer.Timer;

public class ItemsAutoDestroy {

	protected static final Logger _log = LoggerFactory.getLogger(ItemsAutoDestroy.class.getName());

	protected List<L2ItemInstance> _items;

	protected static long _sleep;

	private Runnable run = new Runnable() {
		public void run() {
			removeItems();
		}
	};

	private ItemsAutoDestroy() {
		_log.info("Initializing ItemsAutoDestroy.",Config.SERVER_ID,"ItemsAutoDestroy");
		_items = new FastList<L2ItemInstance>();
		_sleep = Config.AUTODESTROY_ITEM_AFTER * 1000;
		if (_sleep == 0) // it should not happend as it is not called when AUTODESTROY_ITEM_AFTER = 0 but we never know..
			_sleep = 3600000;
		new Timer(5000, true, run).start();
	}

	public static ItemsAutoDestroy getInstance() {
		return SingletonHolder._instance;
	}

	public void addItem(L2ItemInstance item) {
		item.setDropTime(System.currentTimeMillis());
		_items.add(item);
	}

	public void removeItems() {
		if (_log.isDebugEnabled())
			_log.debug("[ItemsAutoDestroy] : " + _items.size() + " items to check.");

		if (_items.isEmpty())
			return;

		long curtime = System.currentTimeMillis();
		for (L2ItemInstance item : _items) {
			if (item == null || item.getDropTime() == 0 || item.getLocation() != L2ItemInstance.ItemLocation.VOID)
				_items.remove(item);
			else {
				if ((curtime - item.getDropTime()) > _sleep) {
					item.decayMe();
					_items.remove(item);
					if (Config.SAVE_DROPPED_ITEM)
						ItemsOnGroundManager.getInstance().removeObject(item);
				}
			}
		}

		if (_log.isDebugEnabled())
			_log.debug("[ItemsAutoDestroy] : " + _items.size() + " items remaining.");
	}

	@SuppressWarnings("synthetic-access")
	private static class SingletonHolder {
		protected static final ItemsAutoDestroy _instance = new ItemsAutoDestroy();
	}
}